/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.bsuir.bbs.dao;

import by.bsuir.bbs.dao.exceptions.IllegalOrphanException;
import by.bsuir.bbs.dao.exceptions.NonexistentEntityException;
import by.bsuir.bbs.dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import by.bsuir.bbs.persistence.Ad;
import by.bsuir.bbs.persistence.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;

/**
 *
 * @author Администратор
 */
public class UserJpaController implements Serializable {

    public UserJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;
    private Context ctx;
    protected EntityManager em;
public UserJpaController() {
        try {
            this.emf = Persistence.createEntityManagerFactory("BulletinBoardSystemPU");
            this.em = emf.createEntityManager();
            this.ctx = new InitialContext();
            this.utx = (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");
        } catch (NamingException ex) {
            Logger.getLogger(UserJpaController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) throws RollbackFailureException, Exception {
        if (user.getAdCollection() == null) {
            user.setAdCollection(new ArrayList<Ad>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Ad> attachedAdCollection = new ArrayList<Ad>();
            for (Ad adCollectionAdToAttach : user.getAdCollection()) {
                adCollectionAdToAttach = em.getReference(adCollectionAdToAttach.getClass(), adCollectionAdToAttach.getAdPK());
                attachedAdCollection.add(adCollectionAdToAttach);
            }
            user.setAdCollection(attachedAdCollection);
            em.persist(user);
            for (Ad adCollectionAd : user.getAdCollection()) {
                User oldUserOfAdCollectionAd = adCollectionAd.getUser();
                adCollectionAd.setUser(user);
                adCollectionAd = em.merge(adCollectionAd);
                if (oldUserOfAdCollectionAd != null) {
                    oldUserOfAdCollectionAd.getAdCollection().remove(adCollectionAd);
                    oldUserOfAdCollectionAd = em.merge(oldUserOfAdCollectionAd);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User persistentUser = em.find(User.class, user.getUserId());
            Collection<Ad> adCollectionOld = persistentUser.getAdCollection();
            Collection<Ad> adCollectionNew = user.getAdCollection();
            List<String> illegalOrphanMessages = null;
            for (Ad adCollectionOldAd : adCollectionOld) {
                if (!adCollectionNew.contains(adCollectionOldAd)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Ad " + adCollectionOldAd + " since its user field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Ad> attachedAdCollectionNew = new ArrayList<Ad>();
            for (Ad adCollectionNewAdToAttach : adCollectionNew) {
                adCollectionNewAdToAttach = em.getReference(adCollectionNewAdToAttach.getClass(), adCollectionNewAdToAttach.getAdPK());
                attachedAdCollectionNew.add(adCollectionNewAdToAttach);
            }
            adCollectionNew = attachedAdCollectionNew;
            user.setAdCollection(adCollectionNew);
            user = em.merge(user);
            for (Ad adCollectionNewAd : adCollectionNew) {
                if (!adCollectionOld.contains(adCollectionNewAd)) {
                    User oldUserOfAdCollectionNewAd = adCollectionNewAd.getUser();
                    adCollectionNewAd.setUser(user);
                    adCollectionNewAd = em.merge(adCollectionNewAd);
                    if (oldUserOfAdCollectionNewAd != null && !oldUserOfAdCollectionNewAd.equals(user)) {
                        oldUserOfAdCollectionNewAd.getAdCollection().remove(adCollectionNewAd);
                        oldUserOfAdCollectionNewAd = em.merge(oldUserOfAdCollectionNewAd);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getUserId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getUserId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Ad> adCollectionOrphanCheck = user.getAdCollection();
            for (Ad adCollectionOrphanCheckAd : adCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Ad " + adCollectionOrphanCheckAd + " in its adCollection field has a non-nullable user field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(user);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
     public List<User> view() {
        Query query = em.createNamedQuery("User.findAll");
        return query.getResultList();
    }
     
     public List<User> findUserByLogin(String login) {
        Query query = em.createQuery("SELECT u FROM User u WHERE u.login = :login");
        query.setParameter("login", login);
        return query.getResultList();
    }
}
